import store from '../store/store';
/**
 * 定义问诊中收发的数据包类型
 * @type
 */
/**
 * 1	登录	{"token":"web_token_P_140_Gey2923pMGDq2tnFmpBDpQNT3PSBt5NXLmjqrBC_","packageType":"1"}
 * 2	邀请用户加入房间	{ "receiverID": 1,  "receiverType": "doctor", "roomId": 1, "message": "邀请你加入会诊",  "timestamp": 1729067939654,  "packageType": 2 }
 * 3	加入房间	{"roomId":1,"packageType":3,"timestamp":1729067560440}
 * 4	聊天消息	{"content":"你好","packageType":4,"contentType":2,"roomId":1,"timestamp":1729067560440}
 * @type {{login: number}}
 */
const dataType = {
  login: 1, // 登陆请求
  invite: 2, // 邀请用户加入房间
  join: 3, // 加入房间
  chat: 4, // 聊天消息
  logout: 5, // 退出登录
};

const wsConnection = {
  heartbeatTime: 8000, // 心跳时间
  wsUrl: '',
  token: '',
  ws: {},
  intervalId: 0, // 心跳定时器id
  ttId: 0,
  lock: false,
  initWebSocket(wsUrl, token) {
    if (wsUrl) {
      this.wsUrl = wsUrl;
    }
    if (token) {
      this.token = token;
    }
    const that = this;
    this.ws = new WebSocket(this.wsUrl);
    this.ws.onopen = this.onOpen.bind(this);
    this.ws.onmessage = function (event) {
      console.log('消息事件', event.data);
      if (typeof event.data === 'string') {
        let content = event.data;
        if (content.indexOf('{') === 0) {
          content = JSON.parse(content);
          console.log('消息事件', content);
          that.onMessage(content);
        }
      }
    };
    this.ws.onclose = this.onClose.bind(this);
    this.ws.onerror = this.onError.bind(this);
  },
  onOpen(event) {
    this.login();
    this.resetHeartbeat();
  },
  onMessage(msg) {
    if (msg.packageType == 1 && msg.packageCode == 0) {
      /* --- test:退出登录后，清除定时器和销毁socket --- */
      this.ttId && clearTimeout(this.ttId);
      this.intervalId > 0 && clearInterval(this.intervalId);
      this.onClose();
    } else {
      store.commit('webSocketMsgRemote', msg);
    }
  },
  onClose(evt) {
    if (evt && evt.code !== 1000) {
      this.reconnect();
    }
  },
  onError(ev) {
    this.reconnect();
  },
  login() {
    // 进行登录认证
    this.send(dataType.login, { token: this.token });
  },
  logout(data) {
    this.ttId && clearTimeout(this.ttId);
    this.intervalId > 0 && clearInterval(this.intervalId);
    this.send(2, data); // TODO退出登录的type
    this.onClose();
  },

  reconnect() {
    if (this.lock) {
      return;
    }
    this.lock = true;
    const that = this;

    this.ttId && clearTimeout(this.ttId);

    this.ttId = setTimeout(() => {
      that.initWebSocket();
      that.lock = false;
    }, 3000);
  },
  startWsHeartbeat() {
    const that = this;
    this.intervalId = setInterval(() => {
      // 判断websocket当前状态
      // 0 ：对应常量 正在建立连接连接，还没有完成。
      // 1 ：对应常量OPEN   连接成功建立，可以进行通信。
      // 2 ：对应常量CLOSING  连接正在进行关闭握手，即将关闭。
      // 3 : 对应常量CLOSED  连接已经关闭或者根本没有建立。
      if (that.ws.readyState === 1) {
        that.ws.send('ping'); // 心跳包
      }
    }, this.heartbeatTime);
  },
  resetHeartbeat() {
    this.ttId && clearTimeout(this.ttId);
    this.intervalId > 0 && clearInterval(this.intervalId);
    this.startWsHeartbeat();
  },
  /**
     *
     * @param type 信息包类型
     * @param data 发送的需要发送的数据
     */
  send(type, data) {
    if (!data) {
      data = {};
    }
    data.packageType = type;
    if (this.ws.readyState !== 1) {
      return;
    }
    console.log('------- 远程会诊发送数据', type, data);
    data = JSON.stringify(data);
    this.ws.send(data);
  },

};


// //抛出websocket对象
export default wsConnection;


/**
 * 远程会诊socket
 * 1	登录	{"token":"web_token_P_140_Gey2923pMGDq2tnFmpBDpQNT3PSBt5NXLmjqrBC_","packageType":"1"}
 * 2	邀请用户加入房间	{ "receiverID": 1,  "receiverType": "doctor", "roomId": 1, "message": "邀请你加入会诊",  "timestamp": 1729067939654,  "packageType": 2 }
 * 3	加入房间	{"roomId":1,"packageType":3,"timestamp":1729067560440}
 * 4	聊天消息	{"content":"你好","packageType":4,"contentType":2,"roomId":1,"timestamp":1729067560440}
 * +++ 登录 +++
 * {"userId":1,"code":1,"userName":"test","userType":"doctor"} 如需要视频的sign可以添加该字段
 * +++ 受到邀请加入房间 +++
 * {"roomId":1,"userId":1,"code":1,"userType":"doctor","content":"xx医生邀请你加入会诊"}
 * +++加入房间+++
 * 房间内广播系统消息
 * ++ 聊天信息 ++
 * 图片 {"content":"https://nxk.aliyuncs.com/381406.jpg","code":4,"contentType":1,"roomId":1,"timestamp":1729067560440}
 * 文本{"content":"你好","code":4,"contentType":2,"roomId":1,"timestamp":1729067560440}
 * 视频 {"content":"https://nxk.aliyuncs.com/a.mp4","code":4,"contentType":3,"roomId":1,"timestamp":1729067560440}
 *
 * 内容类型	枚举值(contentType)
 * 图片消息	1
 * 文本消息	2
 * 视频消息	3
 * 音频消息	4
 * 系统消息	5
 */
